package com.leoman.filter;

import com.leoman.common.logger.Logger;
import com.leoman.core.Constant;
import com.leoman.entity.User;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangbin on 2015/8/4.
 */
public class WeixinLoginFilter implements Filter {

    private static String[] SKIP_URLS = new String[]{};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String urls = filterConfig.getInitParameter("skipUrls");
        if (StringUtils.isNotBlank(urls)) {
            String temp[] = urls.split(",");
            List<String> list = new ArrayList<String>();

            for (String skipUrl : temp) {
                if (StringUtils.isNotBlank(skipUrl)) {
                    skipUrl = "^" + skipUrl.replaceAll("\\*", ".*") + "$";
                    list.add(skipUrl);
                }
            }
            SKIP_URLS = list.toArray(SKIP_URLS);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        try {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            String url = httpRequest.getRequestURI().toString();
            String contextPath = httpRequest.getContextPath();
            String queryString = httpRequest.getQueryString();
            url = url.substring(contextPath.length());
            Logger.info(contextPath + ", " + url + "," + queryString);
            Logger.info("url:" + httpRequest.getRequestURL());

            if (SKIP_URLS != null) {
                for (String skipUrl : SKIP_URLS) {
                    Pattern pattern = Pattern.compile(skipUrl, Pattern.DOTALL);
                    Matcher matcher = pattern.matcher(url);
                    if (matcher.find()) {
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
            System.out.println("=======================WeixinLoginFilter==============================");
            User kUser = (User) httpRequest.getSession().getAttribute(Constant.SESSION_WEIXIN_USER);
            if (null == kUser) {
                Logger.info("urlkUser:" + httpRequest.getQueryString());
                String parmas = httpRequest.getQueryString();
                String goUrl = httpRequest.getRequestURL() + (StringUtils.isNotBlank(parmas) ? "?" + parmas : "");
                System.out.println("goUrl:" + goUrl);
                if (goUrl.contains("weixin/product/snapUp")) {
                    goUrl = httpRequest.getContextPath() + "/weixin/product/detail" + (StringUtils.isNotBlank(parmas) ? parmas : "");
                    System.out.println("snapUp to detail url :" + goUrl);
                }
                httpRequest.getSession().setAttribute(Constant.GO_URL, goUrl);

                String params = "";
                if (goUrl.indexOf("?") != -1) {
                    params = goUrl.substring(goUrl.indexOf("?"), goUrl.length());
                }
                final String toLoginUrl = httpRequest.getContextPath() + "/weixin/login/toLogin" + params;
                System.out.println("toLoginUrl:" + toLoginUrl);
                httpResponse.sendRedirect(toLoginUrl);
                chain.doFilter(request, response);
                return;
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {

    }
}
